package org.xserver.component.core.filter;

import org.xserver.component.core.XServerHttpContextAttachment;

public class ApplicationFilterChain implements FilterChain {

	private FilterConfig[] filters = new FilterConfig[0];
	// filter array size(not array length)
	private int n;
	// the current filter index
	private int position;

	@Override
	public void doFilter(XServerHttpContextAttachment attachment)
			throws XServerFilterException {
		if (position < n) {
			filters[position++].getFilter().doFilter(attachment, this);
		}
	}

	/**
	 * Add a filter to the set of filters that will be executed in this chain.
	 * 
	 * @param filterConfig
	 */
	public void addFilter(FilterConfig filterConfig) {
		for (FilterConfig filter : filters) {
			if (filter == filterConfig) {
				return;
			}
		}

		// if the array is full, we add 10 size to array
		if (n == filters.length) {
			FilterConfig[] newFilters = new FilterConfig[n + 10];
			System.arraycopy(filters, 0, newFilters, 0, n);
			filters = newFilters;
		}

		filters[(n++)] = filterConfig;
	}

//	public ApplicationFilterChain getApplicationFilterChain() {
//
//	}
}
